<?php

namespace app\admin\model;

use think\Model;
use think\Db;
class CategoryModel extends Model
{
    // 确定链接表名
    protected $table='wk_category';

    // 查询分类
    public function getcatelist($where,$limit,$offset)
    {
       return $this->field('id,cate_name,status')->order('sort desc')->limit($offset, $limit)->where($where)->select();
    }
    //添加分类
    public function insertCate($param)
    {
        try{
            $result =  $this->validate('CateValidate')->save($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('admin/Category/index'), '添加分类成功');
            }
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }
    }
    
    //编辑分类
    public function editCate($param)
    {
        try{
            $result = $this->validate('CateValidate')->save($param, ['id' => $param['id']]);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('admin/Category/index'), '编辑分类成功');
            }
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    //根据id查询分类信息
    public function getOneCate($id)
    {
        return $this->field('id,cate_name,sort,status')->where('id',$id)->find();
    }

    // 查询总页数
    public function getAllCate($where)
    {
        return $this->where($where)->count();
    }
    
    // 添加子分类时查询父分类的信息
    public function getCatePid($id)
    {
        return $this->field('id,cate_name')->where('id',$id)->find();
    }
    
    //查看子分类
    public function getcateChildlist()
    {

    }

    //将分类按顺序排序
    public function catelist()
    {
        $res = Db::name('category')
            ->field("cate_name,id,concat(path,id) as px,pid")
            ->where(['status'=>1])
            ->order('px')
            ->select();
        foreach ($res as $k => $v) {
            // 1. 统计逗号的个数 $num
            $num = substr_count($v['px'], ',');
            // 2. 将空格 重复$num次
            $nbsp = str_repeat('&nbsp&nbsp&nbsp', ($num-1)*2);
            // 3. 将空格 塞到$res
            $res[$k]['nbsp'] = $nbsp;
        }
        return $res;
    }

    public function delCate($id)
    {
        $data=[];
        $childcate=$this->field('id')->where('pid',$id)->find();
        if ($childcate){
            return $data=['code'=>'0','data'=>$childcate['id'],'msg'=>'该分类下有子分类,请先删除子分类'];
        }
        $delcate=$this->where('id',$id)->delete();
        if ($delcate){
            return $data=['code'=>'1','data'=>$delcate,'msg'=>'删除成功'];
        }

    }


}
